﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace DataBaseBackUpUtil
{
    public class BackUpUtil
    {
        public static void StartCmd(String workingDirectory, String command,EventHandler FinsishEvent)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.EnableRaisingEvents = true;                      // 启用Exited事件  
            p.Exited += FinsishEvent;   // 注册进程结束事件  
            p.Start();
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
        }
        public static void BackUpDB(string MySqlInstallPath, string BackUpFolderPath, string UserName, string Password, string DataBaseName, ref string BackUpFilePath,EventHandler FinsishEvent)
        {
            try
            {
                //String command = "mysqldump --quick --host=localhost --default-character-set=gb2312 --lock-tables --verbose  --force --port=端口号 --user=用户名 --password=密码 数据库名 -r 备份到的地址";
                //构建执行的命令
                StringBuilder sbcommand = new StringBuilder();

                StringBuilder sbfileName = new StringBuilder();
                sbfileName.AppendFormat("{0}", DataBaseName + DateTime.Now.ToShortDateString()).Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
                String fileName = sbfileName.ToString();
                String directory = BackUpFolderPath + fileName + ".bak";
                BackUpFilePath = directory;
                sbcommand.AppendFormat("mysqldump --quick --host=localhost --default-character-set=utf8 --lock-tables --verbose  --force --port=3306 --user={0} --password={1} {2} -r \"{3}\"", UserName, Password, DataBaseName, directory);
                String command = sbcommand.ToString();

                //获取mysqldump.exe所在路径
                StartCmd(MySqlInstallPath, command, FinsishEvent);
                FLog.WriteLog("备份成功！");
            }
            catch (Exception ex)
            {
                FLog.WriteLog("备份失败！异常信息：" + ex.Message);
            }
        }
    }
}
